from flask import Flask, render_template, url_for, session, redirect, flash
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from datetime import datetime
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

class NameForm(FlaskForm):
    name = StringField('你叫什么名字？', validators=[DataRequired()])
    submit = SubmitField('提交')
    
app = Flask(__name__)

app.config['SECRET_KEY'] = '1234567890'
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://你的数据库用户名:密码@localhost/你的数据库'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

bootstrap = Bootstrap(app)
moment = Moment(app)
db = SQLAlchemy(app)
migrate = Migrate(app, db)

class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    users = db.relationship('User', backref='role', lazy='dynamic')
    def __repr__(self):
        return '<Role %r>' % self.name

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    def __repr__(self):
        return '<User %r>' % self.username


@app.route('/', methods=['GET', 'POST'])
def index():
    # name = None
    nameform = NameForm()
    if nameform.validate_on_submit():
        user = User.query.filter_by(username=nameform.name.data).first()
        if user is None:
            user = User(username=nameform.name.data)
            db.session.add(user)
            db.session.commit()
            session['known'] = False
            flash('很高兴见到你', 'danger')
        else:
            session['known'] = True
            flash('很荣幸再见到你', 'success')
        # old_name = session.get('name')
        # if old_name is not None and old_name != nameform.name.data:
        #     flash('你修改了姓名！', 'danger')
        session['name'] = nameform.name.data
        nameform.name.data = ''
        return redirect(url_for('index'))
    return render_template('index.html', name=session.get('name'), nameform=nameform,known=session.get('known', False), current_time=datetime.utcnow())

@app.route('/user/<name>')
def user(name):
    return render_template('user.html', name=name)

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

@app.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'), 500

@app.shell_context_processor
def make_shell_context():
    return dict(db=db, User=User, Role=Role)
